package app.controllers;

import app.Const;
import app.models.app.ProductRecommend;
import app.models.app.TopShuffling;
import app.models.product.Product;
import com.google.common.base.Strings;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import goja.mvc.Controller;
import goja.rapid.datatables.DTCriterias;
import goja.rapid.db.DaoKit;
import org.joda.time.DateTime;

import java.util.List;

/**
 * <p>
 * APP顶部轮播
 * </p>
 *
 * @author liuhui
 * @version 1.0
 * @since JDK 1.6
 */
public class BannerController extends Controller {

    public void index(){}

    /**
     * 列表访问
     */
    @Before(GET.class)
    public void dtlist(){
        final DTCriterias criterias = DTCriterias.criteriasWithRequest(getRequest());
        renderDataTables(criterias, TopShuffling.class);
    }

    @Before(GET.class)
    public void create() {
        TopShuffling topShuffling = new TopShuffling();
        List<Product> products = Product.dao.findAllAvailable();
        setAttr("products", products);
        setAttr("banner", topShuffling);
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        render("item.ftl");
    }

    @Before(GET.class)
    public void edit() {
        String id = getPara(0, "0");
        TopShuffling topShuffling = TopShuffling.dao.findById(id);
        List<Product> products = Product.dao.findAllAvailable();
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        setAttr("banner",topShuffling);
        setAttr("products", products);
        render("item.ftl");
    }

    @Before(POST.class)
    public void save() {
        TopShuffling banner = getModel(TopShuffling.class,"banner");

        if (!Strings.isNullOrEmpty(getPara("img_attachment"))) {
            banner.set("img",getPara("img_attachment_url"));
            banner.set("img_attachment",getPara("img_attachment"));
        }
        if (DaoKit.isNew(banner)) {
            banner.set(Const.FIELD_CREATE_TIME,DateTime.now().toDate());
            banner.save();
        } else {
            banner.update();
        }
        redirect("/banner");
    }


    /**
     * 删除
     */
    public void delete(){
        int id = getParaToInt(0, 0);
        boolean status = TopShuffling.dao.deleteById(id);
        if(status){
            renderAjaxSuccess();
        }else {
            renderAjaxFailure();
        }
    }


}
